package leetcod_300;

/**
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * 删除操作：
 * 计算长度
 */

public class leetCode_19_removeNthFromEnd {

    public ListNode removeNthFromEnd(ListNode listNode, int n) {
        ListNode dummy = new ListNode(0, listNode);
        int length = getLength(listNode);
        ListNode cur = dummy;
        for (int i = 1; i < length - n + 1; i++) {
            cur = cur.next;
        }
        cur = cur.next.next;
        ListNode ans = dummy.next;
        return ans;

    }


    public int getLength(ListNode head) {
        int i = 0;
        while (head.next != null) {
            ++i;
            head = head.next;
        }
        return i;
    }


}
